<template>
  <div>
    <slot name="header"></slot>
    <attach-list v-loading="loading" :attath-data="uploadList" :show-label="showLabel">
      <slot v-for="slot in slots" :name="slot" :slot="slot"></slot>

      <template slot="tagAction" slot-scope="{ tagData }">
        <div class="d-flex justify-content-between">
          <el-button
            type="primary"
            size="small"
            class="btn-long mb-1"
            v-if="tagData.otherButton && !viewMode"
            @click="handlerEdit(tagData.tag)"
          >
            {{ tagData.tag === '尽调报告' ? '尽调报告' : '登记' }}
          </el-button>
          <div>
            <el-button
              type="primary"
              size="small"
              class="btn-long mb-1"
              icon="el-icon-upload2"
              v-if="!viewMode && !tagData.uploadable"
              @click="handleUpload(tagData.tag, tagData.parentTag)"
            >
              上传
            </el-button>
            <el-button
              size="small"
              class="btn-long mb-1"
              v-if="tagData.otherButton"
              @click="handlerView(tagData.tag)"
            >
              查看
            </el-button>
          </div>
        </div>
      </template>

      <template slot="attachAction" slot-scope="{ attachData }" v-if="!viewMode">
        <el-button type="text" @click="handleDeleteFile(attachData)">删除</el-button>
      </template>
    </attach-list>

    <attach-upload-dialog
      :visible.sync="uploadVisible"
      :attach-tag="uploadAttachTag"
      :parent-tag="parentTag"
      :attach-id="queryId"
      v-bind="$attrs"
      @success="onUploadSuccess"
    ></attach-upload-dialog>

    <intention-letter
      :visible.sync="intentionEdit"
      :view-mode="viewMode"
      :query-id="queryId"
      @getDocId="getIntentionDocId"
      @getRelated="getRelatedData"
    ></intention-letter>

    <el-dialog
      :visible.sync="docViewVisible"
      :close-on-click-modal="false"
      append-to-body
      top="30px"
      width="80%"
    >
      <pdf-view :contract-id="docId" :view-mode="true" :query-id="queryId"></pdf-view>
    </el-dialog>

    <el-dialog
      :visible.sync="contractViewVisible"
      :close-on-click-modal="false"
      append-to-body
      top="30px"
      width="80%"
    >
      <contract-guard-view :query-id="contractViewId"></contract-guard-view>
    </el-dialog>

    <handle-contract
      :visible.sync="handleContrctVisible"
      :query-id="queryId"
      :view-mode="viewMode"
    ></handle-contract>

    <contract-registr-dialog
      :visible.sync="signTypeVisible"
      :view-mode="signViewMode"
      :query-id="queryId"
    ></contract-registr-dialog>

    <loan-letter
      :visible.sync="sendLoanVisible"
      :related="relatedData"
      :view-mode="viewMode"
      :query-id="queryId"
      @getDocId="getLoanDocId"
    ></loan-letter>

    <report-dialog
      :visible.sync="reportVisible"
      :query-id="queryId"
      :view-mode="reportViewMode"
    ></report-dialog>

    <risk-edit
      :visible.sync="riskVisible"
      :query-id="queryId"
      :view-mode="riskViewMode"
    ></risk-edit>
  </div>
</template>

<script>
import { attachAdapter } from '@/bank/components/attach/index'
import { deleteOss } from '@/common/api/oss'

import AttachList from '@/bank/components/attach/List'
import AttachUploadDialog from '@/bank/components/attach/UploadDialog'

import IntentionLetter from '@/bigcredit/views/self/fast/item/components/letter/IntentionLetter'
import PdfView from '@/credit/views/county/unionProvince/components/PdfView'
import ContractGuardView from '@/credit/views/county/unionProvince/components/ContractGuardView'
import HandleContract from '@/bigcredit/views/program/components/HandleContract'
import ContractRegistrDialog from '@/credit/views/city/self/components/contractRegistr/ContractRegistrDialog'
import LoanLetter from '@/bigcredit/views/self/fast/item/components/letter/LoanLetter'
import ReportDialog from '@/bigcredit/views/program/components/report/IndexDialog'
import RiskEdit from '@/bigcredit/views/self/fast/item/components/RiskEdit'
export default {
  components: {
    AttachList,
    AttachUploadDialog,
    IntentionLetter,
    PdfView,
    ContractGuardView,
    HandleContract,
    ContractRegistrDialog,
    LoanLetter,
    ReportDialog,
    RiskEdit,
  },
  props: {
    queryId: {
      type: String,
      default: '',
    },
    showLabel: {
      type: Boolean,
      default: true,
    },
    viewMode: Boolean,
  },
  data() {
    return {
      tags: [
        { parentTag: '调查附件', tag: '项目审批表', required: false },
        { parentTag: '调查附件', tag: '尽调报告', required: false },
        {
          parentTag: '评审会附件',
          tag: '评审会附件',
          required: false,
        },
        { parentTag: '项目附件', tag: '担保意向函', required: false, otherButton: true },
        {
          parentTag: '项目附件',
          tag: '风险金登记',
          required: false,
          otherButton: true,
          uploadable: true,
        },
        { parentTag: '项目附件', tag: '合同处理', required: false, otherButton: true },
        {
          parentTag: '项目附件',
          tag: '签约登记',
          required: false,
          otherButton: true,
          uploadable: true,
        },
        { parentTag: '项目附件', tag: '放款通知书', required: false, otherButton: true },
      ],
      tableName: 'datum_customer_attachment',
      loading: false,
      uploadList: [],

      uploadAttachTag: '',
      parentTag: '',
      uploadVisible: false,
      attachTableData: [],

      intentionEdit: false,
      intentionDocId: '',
      docViewVisible: false,
      docId: '',
      contractViewVisible: false,
      contractViewId: '',

      handleContrctVisible: false,

      signTypeVisible: false,
      signViewMode: true,

      sendLoanVisible: false,

      reportVisible: false,
      reportViewMode: false,
      loanDocId: '',
      relatedData: {},

      riskVisible: false,
      riskViewMode: false,
    }
  },
  computed: {
    uploadTags() {
      const tags = this.tags.map(item => {
        return { ...item }
      })
      if (+this.relatedData.form_type === 1) {
        tags.map(item => {
          if (item.tag === '尽调报告') {
            item.otherButton = true
          }
          return item
        })
      }
      return tags
    },
    slots() {
      const res = []
      for (const tag of this.uploadTags) {
        if (tag.slot) res.push(tag.slot)
      }
      return res
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.init()
      },
      immediate: true,
    },
    uploadTags() {
      this.initAttach()
    },
  },
  created() {},
  mounted() {},
  methods: {
    handlerView(tag) {
      switch (tag) {
        case '风险金登记': {
          this.riskVisible = true
          this.riskViewMode = true
          return
        }
        case '担保意向函': {
          this.docId = this.intentionDocId
          this.docViewVisible = true
          return
        }
        case '合同处理': {
          this.contractViewVisible = true
          this.contractViewId = this.queryId
          return
        }
        case '签约登记': {
          this.signTypeVisible = true
          this.signViewMode = true
          return
        }
        case '放款通知书': {
          this.docId = this.loanDocId
          this.docViewVisible = true
          return
        }
        case '尽调报告': {
          this.reportVisible = true
          this.reportViewMode = true
          return
        }
      }
    },
    handlerEdit(tag) {
      switch (tag) {
        case '风险金登记': {
          this.riskVisible = true
          this.riskViewMode = false
          return
        }
        case '担保意向函': {
          this.intentionEdit = true
          return
        }
        case '合同处理': {
          this.handleContrctVisible = true
          return
        }
        case '签约登记': {
          this.signTypeVisible = true
          this.signViewMode = false
          return
        }
        case '放款通知书': {
          this.sendLoanVisible = true
          return
        }
        case '尽调报告': {
          this.reportVisible = true
          this.reportViewMode = false
          return
        }
      }
    },
    getLoanDocId(id) {
      this.loanDocId = id
    },
    getRelatedData(data) {
      this.relatedData = { ...data }
      this.$emit('getRelated', data)
    },
    getIntentionDocId(id) {
      this.intentionDocId = id
    },
    init() {
      this.reset()
      this.getData()
    },
    initAttach() {
      this.reset()
      for (const attach of this.attachTableData) {
        const attachData = attachAdapter(attach)

        let index = this.uploadList.findIndex(it => it.tag === attach.attachment_type)
        if (index < 0) {
          continue
        }
        this.uploadList[index].attachs.push(attachData)
      }
    },
    async getData(emit = false) {
      if (!this.queryId) {
        return
      }

      this.loading = true
      this.$api
        .getData(
          this.$serviceName,
          this.tableName,
          { 'customer_related_id.eq': this.queryId },
          { create_time: 'desc' }
        )
        .then(res => {
          const data = res?.data ?? []
          this.attachTableData = data
          this.reset()

          for (const attach of data) {
            const attachData = attachAdapter(attach)

            let index = this.uploadList.findIndex(it => it.tag === attach.attachment_type)
            if (index < 0) {
              continue
            }
            this.uploadList[index].attachs.push(attachData)
          }

          this.$emit('after-data', {
            list: data,
            emit,
          })
        })
        .finally(() => {
          this.loading = false
        })
    },

    reset() {
      this.uploadList = this.uploadTags.map(tag => ({
        ...tag,
        attachs: [],
      }))
    },

    handleUpload(tag, parentTag) {
      this.parentTag = parentTag
      this.uploadAttachTag = tag
      this.uploadVisible = true
    },

    onUploadSuccess(res) {
      this.getData(true)
      this.$emit('success', res)
    },

    handleDeleteFile(attach) {
      const { attachment: url, id } = attach
      this.$utils
        .msgbox({
          message: '确定删除此附件?',
          beforeClose: () => this.deleteData(id),
        })
        .then(() => {
          deleteOss(url)
          this.$message.success('删除成功！')
          this.getData(true)
          this.$emit('delete', attach)
        })
        .catch(err => {
          this.$message.error('删除失败，请重试！')
          throw new Error(err)
        })
    },

    deleteData(id) {
      return this.$api.deleteData(this.$serviceName, this.tableName, id)
    },
  },
}
</script>

<style lang="scss" scoped></style>
